package active

import (
	"server/game/cache"
	"server/share/config"

	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/errors"
)

func init() {
	Register(&reward{})
}

// Attach 通用活动记录
type reward struct {
}

func (this *reward) Caller(node *registry.Node, handle *context.Context) interface{} {
	f := node.Method().(func(*reward, *context.Context) interface{})
	return f(this, handle)
}

// Submit 提交任务
//
// id 活动id,参考活动总控中的列表
//
// key Reward ID
func (this *reward) Submit(c *context.Context) any {
	id := c.GetInt32("id")
	key := c.GetInt32("key")
	if key <= 0 {
		return errors.ErrArgEmpty
	}
	ac := config.Data.Active[id]
	if ac == nil {
		return errors.ErrConfigEmpty
	}
	if ac.Mod != config.Data.ActiveMod.Reward {
		return c.Errorf(0, "active config mod mismatched")
	}

	if len(ac.Args) == 0 {
		return c.Errorf(0, "active config args empty")
	}
	rc := config.Data.Reward[key]
	if rc == nil {
		return errors.ErrConfigEmpty
	}
	if rc.Group != ac.Args[0] {
		return c.Error("Active key error")
	}

	handle := cache.GetActive(c.Player.Updater)
	item, _, err := handle.Verify(id)
	if err != nil {
		return err
	}

	data := map[int32]int64{}
	if err = item.Unmarshal(&data); err != nil {
		return err
	}
	if _, ok := data[key]; ok {
		return c.Errorf(0, "active reward is exist")
	}
	data[key] = c.Unix()

	handle.SetAttach(item.OID, data)
	c.Player.AddItems(rc.Item)
	//c.Player.Verify.Auto(Target(rc, cycle))
	if rc.Score > 0 {
		c.Player.Emit(config.Data.Events.Score, rc.Score)
	}
	return true
}
